package digimon.scheduler;

import java.util.LinkedList;
import java.util.Queue;

import digimon.organism.BodyOrganism;
import digimon.organism.Organism;

/**
 * Scheduler to select organisms to execute
 * @author danielm
 *
 */
public class Scheduler {
	Queue<Organism> orgQueue;
	BodyOrganism bodyOrganism;
	
	/**
	 * Default constructor
	 * @param bodyOrganism
	 */
	Scheduler(BodyOrganism bodyOrganism){
		//TODO using a linkedList, maybe a better implementation can use PriorityQueue
		orgQueue = new LinkedList<Organism>() {
			// Auto Generated versionUUID. Don't know what this is for
			private static final long serialVersionUID = 8829537437738395719L;
		};
		this.bodyOrganism = bodyOrganism;
		// Fist, add all organisms on queue
		for(int i = 0; i < bodyOrganism.BODY_SIZE_X; i++)
			for (int j = 0; j < bodyOrganism.BODY_SIZE_Y; j++)
				orgQueue.add(bodyOrganism.getBodyCells()[i][j]);
	}
	
	public void addToQueue(Organism org){
		orgQueue.add(org);
	}
	
	public void removeFromQueue(Organism org){
		orgQueue.remove(org);
	}
	
	/**
	 * This method return the next organism to run
	 * @return the organism that will be executed
	 */
	synchronized public Organism getOrganismToRun(){
		int pri = orgQueue.peek().getPriority();
		// If the organism has a normal priority
		// Return this element and remove it from the queue
		if(pri==0)
			return orgQueue.poll();
		// If not, we decrease the priority and return element without remove it from queue 
		else {
			orgQueue.peek().setPriority(pri-1);
			return orgQueue.peek();
		}
			
	}

}
